package com.zues.samples.service.Impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zues.samples.dao.SubjectDAO;
import com.zues.samples.dao.UserDAO;
import com.zues.samples.dao.UserSubjectDAO;
import com.zues.samples.model.PagerModel;
import com.zues.samples.model.Subject;
import com.zues.samples.service.SubjectService;
import com.zues.samples.service.modelVO.SubjectVO;

@Service
public class SubjectSeviceImpl implements SubjectService {

	@Autowired
	private SubjectDAO subjectDAO;
	
	@Autowired
	private UserDAO UserDAO;
	
	@Autowired
	private UserSubjectDAO userSubjectDAO;

	@Override
	public List<Subject> findAllSubjects() throws Exception {
		return subjectDAO.findAllSubjects();
	}

	@Override
	public Subject getByIdSubject(int SubId) throws Exception {
		return subjectDAO.getByIdSubject(SubId);
	}

	@Override
	public void createSubject(Subject sub) throws Exception {
		subjectDAO.createSubject(sub);
	}

	@Override
	public void editSubject(Subject sub) throws Exception {
		subjectDAO.editSubject(sub);
	}

	@Override
	public void deleteSubject(int SubId) throws Exception {
		subjectDAO.deleteSubject(SubId);
	}

	@Override
	public PagerModel<SubjectVO> findAllByPage() {
		return subjectDAO.findAllByPage();
	}

	@Override
	public void saveSubjectStudent(List<String> subjectStudents, Integer subjectId) throws RuntimeException {
		List<String> dbSubjectUserList = UserDAO.getAllUserBySubject(subjectId);
		
		List<String> insertList = new ArrayList<String>();
		List<String> delList = new ArrayList<String>();
		
		//判断哪些是新勾选的学生
		for(String selectedUser : subjectStudents){
			if(!dbSubjectUserList.contains(selectedUser)){
				insertList.add(selectedUser);
			}
		}
		
		//判断哪个本来勾选现在去掉
		for(String selectedUser : dbSubjectUserList){
			if(!subjectStudents.contains(selectedUser)){
				delList.add(selectedUser);
			}
		}
		
		//insertList 分别保存
		userSubjectDAO.insertSubjectUsers(insertList, subjectId);
		
		userSubjectDAO.deleteSubjectUsers(delList, subjectId);
	}

	@Override
	public void updateStatus(Integer SubId, Integer status) throws Exception {
		subjectDAO.updateStatus(SubId, status);
		
	}
	
}
